package com.hzbank.aaronkotlin

import android.content.Context
import androidx.lifecycle.LifecycleOwner
import androidx.lifecycle.Observer
import androidx.work.Constraints
import androidx.work.NetworkType
import androidx.work.OneTimeWorkRequest
import androidx.work.OneTimeWorkRequestBuilder
import androidx.work.WorkInfo
import androidx.work.WorkManager
import androidx.work.WorkRequest
import java.util.UUID

class WorkManagerHelper {

    fun enqueueWorker(context: Context) {
        val workRequest: WorkRequest = OneTimeWorkRequestBuilder<AaronWorker>()
            .setConstraints(Constraints.Builder()
                .setRequiredNetworkType(NetworkType.CONNECTED)
                .build())
            .build()
        WorkManager.getInstance(context).enqueue(workRequest)

        //链式调用
//        WorkManager.getInstance(context)
//            .beginWith(workRequest1)
//            .then(workRequest2)
//            .enqueue()

        //通过 workRequest.id 监听
        if(null == requestIds) requestIds = mutableListOf()
        requestIds.add(workRequest.id)
    }

    fun notifyWorker(context: Context, lifecycleOwner: LifecycleOwner){

        //监听
        WorkManager.getInstance(context).getWorkInfoByIdLiveData(requestIds[0])
            .observe(lifecycleOwner, Observer {

                it?.let {
                    when(it.state){

                        WorkInfo.State.RUNNING -> {

                            //执行中

                        }
                        WorkInfo.State.SUCCEEDED -> {
                            //执行成功

                        }
                        WorkInfo.State.FAILED -> {
                            //执行失败


                        }
                        else -> {

                        }
                    }
                }

            })

    }


    companion object{


        var requestIds: MutableList<UUID> = mutableListOf()

        private var workInstance: WorkManagerHelper? = null

        fun getInstance(): WorkManagerHelper{
            return workInstance?: synchronized(this){
                workInstance?:WorkManagerHelper().also { workInstance = it }
            }

        }
    }
}